import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '../../api/user'
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '../../api/user/style'
import type { UserState } from './type/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token'
import { constantRoute } from '../../router/routes'

let useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: GET_TOKEN()!,
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
    }
  },
  actions: {
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      console.log(result)
      if (result.code === 200) {
        this.token = result.data as string
        SET_TOKEN(this.token as string)
        return '登录成功'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      let result: userInfoResponseData = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(result.message)
      }
    },
    async userLogout() {
      let result: any = await reqLogout()
      console.log(result)
      if (result.code == 200) {
        this.username = ''
        this.avatar = ''
        this.token = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
export default useUserStore
